package com.yz.jdd.module.cashier.scanpay;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.Result;
import com.trello.rxlifecycle.ActivityEvent;

import com.yunzong.permissions.OnPermission;
import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yz.jdd.R;
import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.AppUtils;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PayConfig;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.base.utils.Tools;
import com.yz.jdd.module.cashier.CashierActivity;
import com.yz.jdd.module.cashier.result.CloseOrderActivity;
import com.yz.jdd.module.cashier.scanpay.exception.ExceptionContract;
import com.yz.jdd.network.request.Request_Pay;
import com.yz.jdd.scan.ScanEventListener;
import com.yz.jdd.scan.SoftwareScanner;
import com.yz.jdd.scan.view.ViewfinderView;
import com.yz.jdd.voice.AudioPlayerInstance;
import com.yz.jdd.voice.OrderVoice;
import com.yz.jdd.voice.SpeechUtilOffline;
import com.yz.jdd.widget.CountdownLoadingDialog;
import com.yz.jdd.widget.PublicDialog;
import com.yz.jdd.widget.TopDialog;

import java.util.List;

import rx.functions.Action1;

/**
 * Created by shibin on 2017/2/27.
 * 扫码支付页面
 * copy by jmliu on  2019-10-18
 */

public class ScanpayActivity extends BaseActivity implements View.OnClickListener, ScanpayContract.ScanpayView {

    private Activity context = ScanpayActivity.this;
    private ScanpayContract.Presenter scanpayPresenter;
    private SoftwareScanner softwareScanner;
    //支付类型
    private String payType = "";
    //倒计时
    private CountdownLoadingDialog countdownLoadingDialog;
    private boolean isDecoded = true;//一次支付只能扫一次
    private Request_Pay request_pay;

    private TextView tvMoney;
    private TextView tvShopName; //门店名称
    private TextView tvSupportType;// 支持的支付方式
    private TextView bt_payment_code;//底部按钮

    private ViewfinderView viewfinderView;
    private SurfaceView surfaceView;
    private MediaPlayer mediaPlayer;
    private boolean isZero = false;

    private TextView rightNav;
    private ImageView back_nav;
    private PublicDialog huaBeiDialog;
    private String[] payTypes;//支付方式

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        isScan = true;
        super.onCreate(savedInstanceState);
        getCameraPermission();
        try {
            if (PreferencesUtils.getBoolean(this, BaseConfigs.BOOLEAN_LOCAL_RECEIVABLES, true)) {
                AudioPlayerInstance.getInstance(this).say(BaseConfigs.VOICE_SCAN_HINT, "1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getCameraPermission() {
        XXPermissions.with(ScanpayActivity.this)
                //.constantRequest() //可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                .permission(Permission.CAMERA
                ) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        LogUtils.e("=== noPermission: "+isAll);
                        dismissTopDialog();
                        //必要权限
                        if (granted.contains(Permission.CAMERA)) {
                            setContentView(R.layout.activity_scanpay);
                            registerRxbusEvent();
                            initView();
                            initScan();
                        } else {
                            permissionDialog();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        LogUtils.e("=== noPermission: "+quick);
                        dismissTopDialog();
                        if (quick) {
                            showToast("被永久拒绝授权，请手动授予权限");
                            if (denied.contains(Permission.CAMERA)) {
                                permissionDialog();
                            }
                        }else{
                            ScanpayActivity.this.finish();
                        }


                    }

                });
        if (!XXPermissions.isHasPermission(ScanpayActivity.this,Permission.CAMERA)){
            showTopDialog("为了您能正常使用【扫码支付】【设备绑定】功能，需向您申请相机权限。如果不允许，您将无法使用扫码功能。" +
                    "");
        }

    }

    //未授权权限弹出对话框
    public void permissionDialog() {
        final PublicDialog permission = new PublicDialog(ScanpayActivity.this);
        permission.setTitle("请开启相关权限");
        permission.setMessage("为保证扫码收款功能正常使用，请务必开启相机权限!");
        permission.setRightBtn("去设置", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                XXPermissions.gotoPermissionSettings(ScanpayActivity.this);
                permission.dismiss();
            }
        });
        permission.setLeftBtn("取消", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                permission.dismiss();
                ScanpayActivity.this.finish();
            }
        });
        permission.setCancelable(false);
        permission.show();

    }

    private TopDialog topDialog = null;

    public void showTopDialog(String content) {
        topDialog = new TopDialog(this);
        topDialog.setContent(content);
        topDialog.show();
    }

    private void dismissTopDialog() {
        if (topDialog != null) {
            topDialog.dismiss();
            topDialog = null;
        }

    }

    public void initScan() {
        softwareScanner = SoftwareScanner.getInstance(this);
        viewfinderView = findViewById(R.id.viewfinder_view);
        surfaceView = findViewById(R.id.preview_view);
        softwareScanner.init(surfaceView, viewfinderView);
        scanpayPresenter = new ScanpayPresenter(context, ScanpayActivity.this, softwareScanner);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (softwareScanner!=null){
            softwareScanner.stopScan();

        }
    }

    @Override
    protected void onStop() {
        if (scanpayPresenter != null) {
            scanpayPresenter.stopScanner();
        }
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (scanpayPresenter != null) {
//            设置扫码监听
            toScan(true);
        }
    }

    /**
     * RxBus消息接收
     *
     * @author bin
     * @time 2017/2/27
     */
    void registerRxbusEvent() {

//         关单操作...
        /**
         * 收银倒计时到50秒时显示撤销按钮，点击按钮，撤销收款操作(现在改为跳转关单界面 2018-09-26)
         */
        RxBus.with(this).setEvent(Events.EVENT_CANCEL_PAY).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                //撤销收款
                Request_Pay request_pay_send = new Request_Pay();
                request_pay_send.setClientOrderId(scanpayPresenter.getClientOrderId());
                request_pay_send.setOrderId(scanpayPresenter.getOrderId());
                request_pay_send.setPayType(payType);
                request_pay_send.setTotalAmount(request_pay.getTotalAmount());
//                scanpayPresenter.setCanceling(true);
                scanpayPresenter.unsubscribePeriod();
                scanpayPresenter.unsubscribeStatus();
//                scanpayPresenter.cancelOrder(request_pay);
                Intent intent = new Intent(ScanpayActivity.this, CloseOrderActivity.class);
                intent.putExtra("request_pay", request_pay_send);
                // intent.putExtra(PayConfig.INTENT_PAY_DATA, scanpayPresenter.getPayDataBean()); // 传递支付监控数据
                startActivity(intent);
            }
        }).create();
        /**
         * 关闭activity
         */
        RxBus.with(this).setEvent(Events.PAY_COMPETE_TO_CLOSE).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                if (Events.PAY_COMPETE_TO_CLOSE.equals(events.getContent())) {
                    finish();
                }
            }
        }).create();
        /**
         * 倒计时结束-->异常订单撤销-->重试
         */
        RxBus.with(this).setEvent(Events.PAY_WAITING_COUNTDOWN_FINISH).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                if (Events.PAY_WAITING_COUNTDOWN_FINISH.equals(events.code)) {
                    scanpayPresenter.unsubscribePeriod();
                    scanpayPresenter.unsubscribeStatus();

                    if (PreferencesUtils.getBoolean(context, BaseConfigs.BOOLEAN_LOCAL_RECEIVABLES, true)) {
                        if (XXPermissions.isHasPermission(ScanpayActivity.this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(context) != null) {
                            OrderVoice orderVoice = new OrderVoice();
                            orderVoice.setContent("收款结果未知");
                            SpeechUtilOffline.getInstance(context).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                        }
                    }
                }
            }
        }).create();
    }

    void initView() {

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(completionListener);
        request_pay = (Request_Pay) getIntent().getSerializableExtra(PayConfig.INTENT_ORDER_FROM);
        if (request_pay == null) {
            request_pay = new Request_Pay();
        }

        ((TextView) findViewById(R.id.title_nav)).setText("扫码收款");

        tvShopName = (TextView) findViewById(R.id.scanpay_shopname_tv);
        String shopName = PreferencesUtils.getString(this, BaseConfigs.PREF_CASH_SHOPNAME, "");
        if (shopName.length() > 16) {
            shopName = shopName.substring(0, 16) + "...";
        }
        tvShopName.setText(shopName);

        tvMoney = (TextView) findViewById(R.id.pay_money);
        tvMoney.setText(request_pay.getTotalAmount());

        back_nav = findViewById(R.id.back_nav);
        back_nav.setOnClickListener(this);

        rightNav = (TextView) findViewById(R.id.right_nav);
        rightNav.setVisibility(View.VISIBLE);
        Drawable drawable = getResources().getDrawable(R.mipmap.shoukuan_hint);
        rightNav.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
        rightNav.setCompoundDrawablePadding(Tools.dip2px(context, 3));
        rightNav.setText("二维码收款");
        rightNav.setOnClickListener(this);


        String cash_paytypes = PreferencesUtils.getString(MyApplication.application, BaseConfigs.PREF_CASH_PAYTYPES, "");
        if (!TextUtils.isEmpty(cash_paytypes)) {
            payTypes = cash_paytypes.split("#");
            if (payTypes != null && payTypes.length > 0) {
                for (String type : payTypes) {
                    payTypeViewSet(type);
                }
            }
        }
    }

    /**
     * 根据支付类型展示图标
     *
     * @param type
     */
    private void payTypeViewSet(String type) {
        if ("2".equals(type)) {
            findViewById(R.id.iv_ali).setVisibility(View.VISIBLE);
        }
        if ("5".equals(type)) {
            findViewById(R.id.iv_wechat).setVisibility(View.VISIBLE);
        }
        if ("7".equals(type)) {
            findViewById(R.id.iv_yunshanfu).setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void setPresenter(ExceptionContract.Presenter presenter) {
        if (presenter != null) {
            scanpayPresenter = (ScanpayContract.Presenter) presenter;
        }

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back_nav) {
            finish();
        }
        //进入出示收款码页面
        if (v.getId() == R.id.right_nav) {
            scanpayPresenter.stopScanner();
            Intent intent = new Intent(ScanpayActivity.this, PaymentCodeActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, request_pay);
            intent.putExtras(bundle);
            startActivity(intent);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * @param
     * @author bin
     * @time 2017/2/27
     */
    @Override
    public void setAliQrcode(Bitmap bitmap) {
        //  scanpayPresenter.intervalStatus();
    }

    /**
     * 微信付款二维码
     *
     * @param url
     */
    @Override
    public void setWxQrcode(String url) {

    }

    /**
     * 付款码下载失败
     */
    @Override
    public void qrLoadingFialed(String msg) {
        dismissLoading();
    }

    /**
     * 【重新扫码】
     */
    @Override
    public void restartScanner() {

        if (null != softwareScanner) {
            softwareScanner.startScan(true);
        }
    }


    /**
     * 改变loading框文案
     *
     * @param msg
     */
    @Override
    public void chanageLoadingMsg(String msg) {
        try {
            countdownLoadingDialog.setLoadingMsg(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示强制撤销按钮
     *
     * @param msg
     */
    @Override
    public void showFroceCancelView(String msg) {
        try {
            countdownLoadingDialog.setLoadingMsg(msg);
            countdownLoadingDialog.showCancelButton("关闭订单");
            if (countdownLoadingDialog != null) {
                countdownLoadingDialog.shutDownCount();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void dismissPayLoading() {
        dismissLoading();
    }

    @Override
    public void showPayLoadingNoCancelable(String msg) {
        showLoadingNoCancelable(msg);

    }

    /**
     * 显示倒计时框
     */
    @Override
    public void showCountDownLoading() {
        try {
            countdownLoadingDialog = new CountdownLoadingDialog(this, request_pay.getOrderType());
            countdownLoadingDialog.show();
            countdownLoadingDialog.setCancelable(false);
            countdownLoadingDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                        return true;
                    } else {
                        return false;
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 隐藏倒计时框并终止倒计时
     */
    @Override
    public void dismissCountDownLoading() {
        try {
            if (countdownLoadingDialog != null) {
                countdownLoadingDialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        if (scanpayPresenter != null) {
            scanpayPresenter.unsubscribePeriod();
            scanpayPresenter.unsubscribeStatus();
            scanpayPresenter.stopScanner();
            scanpayPresenter.unsubscribePay();
        }
        if (mediaPlayer != null) {
            //资源释放
            mediaPlayer.release();
            mediaPlayer = null;
        }

        SoftwareScanner.getInstance(this).release();
        super.onDestroy();
    }

    /**
     * UI线程初始化相机
     *
     * @param isScanable
     */
    private void toScan(final boolean isScanable) {
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                softwareScanner.doScan(new ScanEventListener() {
                    @Override
                    public void onSuccess(Result result) {
                        if (result != null && isDecoded) {

                            // 播放扫码成功提示音
                            AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                            int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
                            LogUtils.i(currentVolume + "currentVolume");
                            if (currentVolume == 0) {
                                isZero = true;
                                int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                                am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume / 2, 0);
                                LogUtils.i(maxVolume + "maxVolume" + "//  am.getStreamVolume(AudioManager.STREAM_MUSIC) " + am.getStreamVolume(AudioManager.STREAM_MUSIC));
                            }
                            try {
                                mediaPlayer.reset();
                                mediaPlayer.setDataSource(context, Uri.parse("android.resource://" + context.getPackageName() + "/" + com.yz.jdd.R.raw.scan_success));
                                mediaPlayer.prepare();
                                mediaPlayer.start();
                            } catch (Exception e) {
                                LogUtils.i(e.toString());
                            }
                            if (AppUtils.isAliPay(result.getText()) || AppUtils.isWeixinPay(result.getText()) || AppUtils.isYunShanFuPay(result.getText())) {
                                isDecoded = false;
                                request_pay.setAuthCode(result.getText());
                                request_pay.setSubPayType(PayConfig.TYPE_SUBPAY_TOSCAN);
                                request_pay.setPayType(PayConfig.TYPE_PAY_SCAN);
                                request_pay.setShopId(PreferencesUtils.getString(MyApplication.application, BaseConfigs.PREF_CASH_SHOPID, ""));
                                scanpayPresenter.toPay(request_pay);
                            } else {
                                LogUtils.e("scanpayCode:" + result.getText());
                                showToast("请出示正确的二维码");
                                restartScanner();
                            }
                        }
                    }

                    @Override
                    public void onError() {

                    }
                }, isScanable);
            }
        });

    }

    MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            if (isZero) {
                AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                int volume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
                LogUtils.i(volume + "-------------");
                am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
                LogUtils.i(am.getStreamVolume(AudioManager.STREAM_MUSIC) + "+++++++++++");
            }
        }
    };


    @Override
    public void failureTime(int time) {

    }

    /**
     * 花呗分期扫码出错提示框
     */
    @Override
    public void showHuaBeiDialog() {
        huaBeiDialog = new PublicDialog(this);
        huaBeiDialog.setTitle("");
        huaBeiDialog.setMessage("请提醒顾客使用支付宝支付");
        huaBeiDialog.setLeftBtn("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                restartScanner();
                isDecoded = true;
                huaBeiDialog.dismiss();
            }
        });
        huaBeiDialog.show();
    }

}